package com.binance.gateway.filter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;

import com.binance.authcenter.api.AuthApi;
import com.binance.authcenter.vo.LogoutResponse;
import com.binance.authcenter.vo.UserIdRequest;
import com.binance.gateway.app.base.dto.SessionDto;
import com.binance.gateway.app.base.helper.BaseHelper;
import com.binance.gateway.app.base.helper.SysConfigHelper;
import com.binance.gateway.app.constant.Constant;
import com.binance.master.models.APIResponse;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import lombok.extern.log4j.Log4j2;

/**
 * Created by Fei.Huang on 2018/8/24.
 */
@Log4j2
public abstract class BaseFilter extends ZuulFilter {

    @Resource
    private AuthApi authApi;
    @Autowired
    protected BaseHelper baseHelper;
    @Autowired
    protected SysConfigHelper sysConfigHelper;

    /**
     * 如果已登陆，则踢出
     */
    public void logoutAll() {
        RequestContext ctx = RequestContext.getCurrentContext();
        Long userId = getUserId(ctx.getRequest());
        if (null != userId) {
            UserIdRequest userIdRequest = new UserIdRequest();
            userIdRequest.setUserId(userId);
            try {
                APIResponse<LogoutResponse> apiResponse = authApi.logoutAll(baseHelper.getInstance(userIdRequest));
                if (apiResponse.getStatus() == APIResponse.Status.OK) {
                    log.info("logoutAll done, userId:{}", userId);
                } else {
                    log.warn("logoutAll failed, userId:{}, errorCode:{}", userId, apiResponse.getCode());
                }
            } catch (Exception e) {
                log.warn("logoutAll error:", e);
            }
        }
        ctx.remove(Constant.SESSION_INFO_KEY);
        baseHelper.deleteAllCookiesWhileLogout();
    }

    protected Long getUserId() {
        RequestContext ctx = RequestContext.getCurrentContext();
        return getUserId(ctx.getRequest());
    }

    protected Long getUserId(HttpServletRequest request) {
        SessionDto sessionVo = getSessionVo();
        if (sessionVo != null) {
            return Long.valueOf(sessionVo.getUserId());
            // } else {
            // String token = BaseHelper.getTokenFromCookie(request);
            // if (StringUtils.isBlank(token)) {
            // return null;
            // }
            // AuthRequest authRequest = new AuthRequest();
            // authRequest.setToken(token);
            // try {
            // APIResponse<AuthResponse> apiResponse =
            // authApi.auth(baseHelper.getInstance(authRequest));
            // if (apiResponse.getStatus() == APIResponse.Status.OK) {
            // AuthResponse response = apiResponse.getData();
            // if (StringUtils.isNotBlank(response.getUserId())) {
            // SessionDto sessionDto = new SessionDto();
            // sessionDto.setToken(response.getToken());
            // sessionDto.setCsrfToken(response.getCsrfToken());
            // sessionDto.setEmail(response.getEmail());
            // sessionDto.setUserId(response.getUserId());
            // sessionDto.setLoginTime(response.getLoginTime());
            // RequestContext ctx = RequestContext.getCurrentContext();
            // ctx.set(Constant.SESSION_INFO_KEY, sessionDto);
            // return Long.valueOf(response.getUserId());
            // }
            // }
            // } catch (Exception e) {
            // log.warn("getUserId error:", e);
            // }
        }
        return null;
    }

    private SessionDto getSessionVo() {
        RequestContext ctx = RequestContext.getCurrentContext();
        return (SessionDto) ctx.get(Constant.SESSION_INFO_KEY);
    }

}
